package com.gist.cithub.service.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.*;

//import com.gist.cithub.service.feign.ServiceFeignService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gist.cithub.service.entity.CombineEntity;
import com.gist.cithub.service.feign.UserFeignService;
import com.gist.cithub.service.utils.ConductorAPI;
import com.gist.cithub.service.utils.HttpRequestor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import com.gist.cithub.service.entity.InforEntity;
import com.gist.cithub.service.service.InforService;
import com.gist.common.utils.PageUtils;
import com.gist.common.utils.R;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;


/**
 * 服务基本信息
 *
 * @author lejin
 * @email sunlightcs@gmail.com
 * @date 2020-11-23 13:29:16
 */
@RefreshScope
@RestController
@RequestMapping("service/infor")
public class InforController {
    @Autowired
    private InforService inforService;
    @Autowired
    UserFeignService serviceFeignService;
    @Value("${imageBaseUrl}")
    private String imageBaseUrl;
    /**
     * 获取类型
     */
    @RequestMapping("/getTypes")
    public R getTypes(){
        List res=inforService.getServiceTypes();
        return R.ok().put("typelist",res);
    }
    /**
     * 根据关键字查询
     */
    @RequestMapping("/searchByKeyword/{keyword}")
    public R info(@PathVariable("keyword") String keyword){
//        Integer userid=infor.getUserId();
//        R nameMap=serviceFeignService.getUserNameById(userid);
        if (keyword.replaceAll(" ","").equals("")){
           return list(null);
        }
        List<InforEntity> servicelist  = inforService.searchByKeyword(keyword);
//        System.out.println("service");
        return R.ok().put("list",servicelist);
    }

    /**
     * 根据类型查询
     */
    @RequestMapping("/searchByType/{type}")
    public R searchByType(@PathVariable("type") String type){
//        Integer userid=infor.getUserId();
//        R nameMap=serviceFeignService.getUserNameById(userid);

        List<InforEntity> servicelist  = inforService.searchByType(type);
//        System.out.println("service");
        return R.ok().put("list",servicelist);
    }
    /**
     * 根据类型和关键字查询
     */
    @RequestMapping("/searchByTypeAndKeyword/{type}/{keyword}")
    public R searchByTypeAndKeyword(@PathVariable("type") String type,@PathVariable("keyword") String keyword){
//        Integer userid=infor.getUserId();
//        R nameMap=serviceFeignService.getUserNameById(userid);

        List<InforEntity> servicelist  = inforService.searchByTypeAndKeyword(type,keyword);
//        System.out.println("service");
        return R.ok().put("list",servicelist);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){

        PageUtils page = inforService.queryPage(params);
        return R.ok().put("list", page.getList());
    }
    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Integer id){
		InforEntity infor = inforService.getById(id);
//		Integer userid=infor.getUserId();
//		R nameMap=serviceFeignService.getUserNameById(userid);
        return R.ok().put("serviceInfor",infor);
    }
    @RequestMapping("/testxjt")
    public void testxjt(){
        for(int i=0;i<10;i++){
            System.out.println("收到数据");

        }
    }

//    /**
//     * 保存
//     */
//    @RequestMapping("/save")
//    public R save(@RequestBody InforEntity infor){
//		inforService.save(infor);
//
//        return R.ok();
//    }
@PostMapping(value = "/uploadService")
public R serviceUpload(@RequestParam("img") MultipartFile img, @RequestParam("service") String service) {
    System.out.println(service);
    JSONObject serviceJson=new JSONObject(JSON.parseObject(service));
    System.out.println(serviceJson.toJSONString());
    String fileName = img.getOriginalFilename();
    System.out.println("上传的文件名为:" + fileName+"服务标题："+serviceJson.getString("title"));
    // 获取文件的后缀名
    String suffixName = fileName.substring(fileName.lastIndexOf("."));
//		System.out.println("上传的后缀名为:" + suffixName);
    //设置文件存放路径http://localhost:63330/restfulapi/serviceImg/3/4/d4db51d7-2b5b-48a9-89fd-97c370c9d605%E6%B1%90.jpg
    String imgPath=imageBaseUrl+getRandomDirectory(fileName);//存入数据库的
    String filePath=System.getProperty("user.dir")+"/serviceImg"+getRandomDirectory(fileName);//创建本地文件的
		System.out.println(filePath);
    fileName = UUID.randomUUID() + fileName;
    File dest = new File(filePath,fileName);
    String imgUrl=(imgPath+"\\"+fileName).replace("\\","/");
    InforEntity sbea=serviceJson.toJavaObject(InforEntity.class);
    sbea.setImg(imgUrl);
    System.out.println(imgUrl);
    //存入数据库
    boolean statusCode = inforService.save(sbea);
//		System.out.println(imgUrl);
    // 检测是否存在目录
    if (!dest.getParentFile().exists()) {
        System.out.print("YES");
        dest.getParentFile().mkdirs();
    }
    else {
        System.out.print("No");
    }
    try {
        img.transferTo(dest);
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return R.ok().put("status",statusCode);
}
    public static String getRandomDirectory(String filename) {

      /* 方法一
       *
       * int hashcode =filename.hashCode();

       // int类型数据在内存中占32位。转换成16进制数，就得到8个16进制数
       String hex =Integer.toHexString(hashcode);

       return "/" +hex.charAt(0) + "/" + hex.charAt(1);*/

        int hashcode = filename.hashCode();

        System.out.println(Integer.toBinaryString(hashcode));

        int a =hashcode & 0xf;

        hashcode = hashcode >>> 4;

        int b =hashcode & 0xf;

        return "/" + a + "/" + b;

    }
    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody InforEntity infor){
		inforService.updateById(infor);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Integer[] ids){
		inforService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }


    @PostMapping("/combine/Sequence")
    public R combination2(HttpServletRequest request) {
        CombineEntity conductorA = inforService.getConductorUrl();
        String ip=conductorA.getIp();
        String port=conductorA.getPort();
        HttpRequestor httpRequestor = new HttpRequestor();
        ConductorAPI conductorAPI = new ConductorAPI(ip, port);
        BufferedReader br;
        StringBuilder sb = null;
        String reqBody = null;
        try {
            br = new BufferedReader(new InputStreamReader(
                    request.getInputStream()));
            String line = null;
            sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            reqBody = URLDecoder.decode(sb.toString(), "UTF-8");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(reqBody);
        JSONArray IdList = jsonObject.getJSONArray("ServiceId");
        int[] ids = new int[IdList.size()];
        for(int i = 0; i < ids.length; i++)
            ids[i] = Integer.parseInt(IdList.get(i).toString());
        List<InforEntity> list = new ArrayList<>();
        for(int i = 0; i < ids.length; i++){
            list.add(inforService.getById(ids[i]));
        }
        jsonObject.remove("ServiceId");
        String workFlowName = conductorAPI.addWorkFlow(list);
        System.out.println(jsonObject.toJSONString());
        String workFlowId = conductorAPI.startWorkFlow(workFlowName, new StringBuffer(jsonObject.toJSONString()));
        String res = conductorAPI.getResult(workFlowId);
        return R.ok().put("data",res);
    }
    @PostMapping(value = "/combine/Parallel")
    public R combination1(HttpServletRequest request) throws InterruptedException {
        CombineEntity conductorA = inforService.getConductorUrl();
        String ip=conductorA.getIp();
        String port=conductorA.getPort();
        HttpRequestor httpRequestor = new HttpRequestor();
        ConductorAPI conductorAPI = new ConductorAPI(ip, port);
        System.out.println("conductorUrl:"+ip+":"+port);
        BufferedReader br;
        StringBuilder sb = null;
        String reqBody = null;
        try {
            br = new BufferedReader(new InputStreamReader(
                    request.getInputStream()));
            String line = null;
            sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            reqBody = URLDecoder.decode(sb.toString(), "UTF-8");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(reqBody);
        System.out.println("reqBody:"+reqBody);
        JSONArray IdList = jsonObject.getJSONArray("ServiceId");
        int[] ids = new int[IdList.size()];
        for(int i = 0; i < ids.length; i++) {
            System.out.println(ids[i]);
            ids[i] = Integer.parseInt(IdList.get(i).toString());
        }
        List<InforEntity> list = new ArrayList<>();
        for(int i = 0; i < ids.length; i++){
            //Service tmp = serviceService.findServiceById(ids[i]);
            //System.out.println(tmp.getUrl());
            list.add(inforService.getById(ids[i]));
        }
        jsonObject.remove("ServiceId");
        String workFlowName = conductorAPI.addForkWorkFlow(list, jsonObject);
        String workFlowId = conductorAPI.startWorkFlow(workFlowName, new StringBuffer("{}"));
//	sleep(1000);
        String res = conductorAPI.getForkTaskResult(workFlowId);
        return R.ok().put("data",res);
    }
}
